package com.yummy.web.security.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.yummy.convention.exception.BusinessException;
import com.yummy.convention.http.DefaultResponseCode;
import com.yummy.security.PermissionMatcher;
import com.yummy.security.RespectableUser;
import com.yummy.web.security.config.FilterPattern;
import com.yummy.web.security.context.RequestContext;

public class AuthorizationFilter extends AbstractSecurityFilter{
	
	private PermissionMatcher permissionMatcher;

	public AuthorizationFilter(FilterPattern filterPattern,PermissionMatcher permissionMatcher) {
		super(filterPattern);
		this.permissionMatcher = permissionMatcher;
	}

	@Override
	protected void sendAccessDenied(ServletRequest request, ServletResponse response) {
		throw new BusinessException(DefaultResponseCode.UNAUTHORIZED.getCode(),DefaultResponseCode.UNAUTHORIZED.getMsg());
	}

	@Override
	protected boolean accessAllowed(ServletRequest request, ServletResponse response) {
		String urlPath = getRequestPath((HttpServletRequest)request);
		return hasPermission(urlPath);
	}
	
	private boolean hasPermission(String urlPath) {
		RespectableUser user = (RespectableUser) RequestContext.getCurrentUser();
		if(user == null) {
			return false;
		}
		return user.hasPermission(permissionMatcher,urlPath);
	}

	protected boolean shouldFilter(ServletRequest request, ServletResponse response) {
		return needLogin(request) && super.shouldFilter(request, response);
	}

	private boolean needLogin(ServletRequest request) {
		Boolean needLogin = (Boolean) request.getAttribute(RequestContext.NEED_LOGIN);
		return needLogin == null || needLogin;
	}

}
